package com.apobates.forum.thrones.admin.controller;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.letterbox.entity.ForumLetterTypeEnum;
import com.apobates.forum.letterbox.entity.proxy.ForumLetterReplica;
import com.apobates.forum.letterbox.service.ForumLetterService;
import com.apobates.forum.letterbox.service.InboxService;
import com.apobates.forum.letterbox.service.OutboxService;
import com.apobates.forum.member.entity.Member;
import com.apobates.forum.member.service.MemberService;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.admin.controller.form.ForumMessageFullForm;
import com.apobates.forum.thrones.admin.exception.ResourceNotFoundException;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.lang.EnumArchitecture;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;

/**
 * 消息控制器
 *
 * @author xiaofanku
 * @since 20190719
 */
@Controller
@RequestMapping(value = "/message")
public class AdminForumMessageController {
    @Autowired
    private InboxService inboxService;
    @Autowired
    private OutboxService outboxService;
    @Autowired
    private ForumLetterService forumLetterService;
    @Autowired
    private MemberService memberService;
    @Value("${site.pageSize}")
    private int pageSize;
    
    //当前管理员收到的消息
    @GetMapping(path = "/")
    public String listInboxPage(
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/message/").addPageSize("number", pageSize);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<ForumLetterReplica> rs = inboxService.getInBox(mbean.getMid(), pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));
        return "admin/message/index";
    }
    
    //当前管理员发送的消息
    @GetMapping(path = "/sent")
    public String listSentPage(
            @RequestParam(value = "p", required = false, defaultValue = "1") int page,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/message/sent").addPageSize("number", pageSize);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<ForumLetterReplica> rs = outboxService.getSent(mbean.getMid(), pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));
        return "admin/message/sent";
    }
    
    //查看
    @GetMapping(path = "/view")
    public String showMessageDetails(
            @RequestParam("id") long id,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        ForumLetterReplica data = forumLetterService.getOneLazyReceiver(id).orElseThrow(()->new ResourceNotFoundException("查看的消息不存在或暂时无法访问"));
        model.addAttribute("letter", data);
        //
        boolean isInbox = false;
        long senderMember = 0;
        String receiver;
        String sender;
        //
        if (data.getAuthor() == mbean.getMid()) { //我发送的消息
            receiver = data.getTargetReceiverNicknames();
            sender = "我";
        } else {
            sender = data.getNickname();
            receiver = "我";
            isInbox = true;
            senderMember = data.getAuthor();
        }
        model.addAttribute("senderMember", senderMember);
        model.addAttribute("isInbox", isInbox);
        model.addAttribute("receiver", receiver);
        model.addAttribute("sender", sender);
        return "admin/message/view";
    }
    
    //新消息
    @GetMapping(path = "/create")
    public String createMessageForm(
            @RequestParam(value = "receiver", required = false, defaultValue = "0") long receiver,
            @RequestParam(value = "names", required = false, defaultValue = "") String receiverNames,
            @RequestParam(value = "label", required = false, defaultValue = "-1") int label,
            HttpServletRequest request,
            Model model) {
        ForumMessageFullForm form = new ForumMessageFullForm();
        if (receiver > 0) {
            form.setUid("u" + receiver);
            form.setSnames(receiverNames);
            form.setLabel(label + "");
        }
        model.addAttribute("form", form);
        return "admin/message/create";
    }
    
    @PostMapping(path = "/create")
    public String createMessageAction(
            @ModelAttribute("form") ForumMessageFullForm form,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        String receiverNickname = "*";
        long receiver = 0L;
        //
        Member m = memberService.get(form.getMemberId()).orElse(null);
        if (null != m) {
            receiverNickname = m.getNickname();
            receiver = m.getId();
        }
        long messageId = forumLetterService.create(form.getEnumLabel(), form.getTitle(), form.getContent(), receiver, receiverNickname, mbean.getMid(), mbean.getNickname());
        if (messageId > 0) {
            return "redirect:/message/sent";
        }
        model.addAttribute("errors", "发送消息操作失败");
        model.addAttribute("form", form);
        return "admin/message/create";
    }
    
    //删除消息(发件人不可以操作)
    @PostMapping(path = "/delete", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removeMessageAction(
            @RequestParam("id") long id,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.of(()->inboxService.remove(mbean.getMid(), Arrays.asList(id)) == 1).success("消息删除成功").error("操作失败");
    }
    
    //阅读消息(发件人不可以操作)
    @PostMapping(path = "/read", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage readMessageAction(
            @RequestParam("id") long id,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.of(()->inboxService.readed(mbean.getMid(), Arrays.asList(id)) == 1).success("消息标记成功").error("操作失败");
    }
    
    @GetMapping(path = "/label/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<Integer, String> getAllRoles(HttpServletRequest request, Model model) {
        //滤掉0
        return EnumArchitecture.getInstance(ForumLetterTypeEnum.class).entrySet().stream().filter(x -> x.getKey() > 0).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
}